package cn.dugcrs.org.service.impl;

import cn.dugcrs.basic.service.impl.BaseServiceImpl;
import cn.dugcrs.basic.utils.MD5Utils;
import cn.dugcrs.basic.utils.StrUtils;
import cn.dugcrs.org.domain.Employee;
import cn.dugcrs.org.mapper.EmployeeMapper;
import cn.dugcrs.org.service.IEmployeeService;
import cn.dugcrs.user.domain.Logininfo;
import cn.dugcrs.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
/**
* @Description:
* @Author: Gubcog
* @Version: 1.0
* @Date:  2022/4/19 18:39  
*/
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    /**
    * @Title: findDrawers
    * @Description: 抽屉查询
    * @Author: Gubcog
    * @Version: 1.0
    * @Date:  2022/4/27 18:00
    * @Parameters: * @param id
    * @Return java.util.List<cn.dugcrs.org.domain.Employee>
    */
    @Override
    public List<Employee> findDrawers(Long id) {
        return employeeMapper.findDrawers(id);
    }

    // 模块的的接口继承而来

    // 模块的其他接口在此编写


    /**
     * 重写新增、级联新增logininfo+权限管理
     * @param employee
     */
    @Override
    public void save(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        String password = MD5Utils.encrypByMd5(employee.getPassword()+ salt);
        employee.setSalt(salt);
        employee.setPassword(password);
        // 级联添加t_logininfo,返回自增id
        Logininfo logininfo = employee2logininfo(employee);
        logininfoMapper.save(logininfo);
        // 新增并返回自增id
        employee.setLogininfo_id(logininfo.getId());
        employeeMapper.save(employee);
        // 通过返回的自增id添加相关联的数据表
        initRelationTable(employee);

    }

    private Logininfo employee2logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        // 设置账号为管理员
        logininfo.setType(0);
        return logininfo;
    }

    private void initRelationTable(Employee employee) {
        // 删除历史数据（冗余的垃圾数据）
        employeeMapper.removeEmployeeRoleByEmployeeId(employee.getId());
        // 保存新的数据
        employeeMapper.saveEmployeeRole(employee.getId(),employee.getRoles());
    }

    /**
     * 重写删除、级联删除ogininfo+权限管理
     * @param id
     */
    @Override
    public void remove(Long id) {
        // 删除权限关联表t_employee相关数据
        employeeMapper.removeEmployeeRoleByEmployeeId(id);
        Employee employee = employeeMapper.loadById(id);
        Long logininfo_id = employee.getLogininfo_id();
        // 删除登录关联表t_logininf相关数据
        logininfoMapper.remove(logininfo_id);
        employeeMapper.remove(id);
    }
}
